package com.example.moblie.poll;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.moblie.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class view_poll extends Fragment implements OnClickListener {

	private LinearLayout linearLayout;
	private Button skipBtn, cmtBtn, numBtn;
	private ImageView image;
	private TextView question;
	private ArrayList<String[]> options = new ArrayList<String[]>();
	private ArrayList<String[]> pollcount = new ArrayList<String[]>();
	private ProgressDialog psDialog;
	Bitmap bitmap;
	private String title = "", cmtcount = "", pollid = "", imageUrl="";
	
	private View thisView;
	@Override
	public View onCreateView(LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState) {

		thisView = inflater.inflate(R.layout.view_poll , container, false);
		
		linearLayout = (LinearLayout) thisView.findViewById(R.id.polloptionlinear);
		skipBtn = (Button) thisView.findViewById(R.id.skipBtn);
		cmtBtn = (Button) thisView.findViewById(R.id.cmtBtn);
		numBtn = (Button) thisView.findViewById(R.id.countBtn);
		image = (ImageView) thisView.findViewById(R.id.image);
		question = (TextView) thisView.findViewById(R.id.question);
		skipBtn.setOnClickListener(this);
		cmtBtn.setOnClickListener(this);
		image.setVisibility(View.GONE);
		//if(getIntent().getStringExtra("pollid") != null)
			//pollid = getIntent().getStringExtra("pollid");
		psDialog = ProgressDialog.show(getActivity(), "", "Loading...");
		poll_connection pollcon = new poll_connection();
		pollcon.execute(pollid);
		
		// Inflate the layout for this fragment
		return thisView;

	}
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);


	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.skipBtn: {
            getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new view_poll()).commit();
			//refresh.putExtra("pollid", "");
			//startActivity(refresh);
			//getActivity().finish();
			break;
		}
		case R.id.cmtBtn: {
			Intent refresh = new Intent(getActivity(), comment.class);
			refresh.putExtra("pollid", pollid);
			refresh.putExtra("title", title);
			getActivity().startActivity(refresh);
			break;
		}
		}
	}

	public void showPoll(){
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);
		
		params.setMargins(15, 5, 15, 5);

			
		
		question.setText(title);
		numBtn.setText(cmtcount);
		if(!imageUrl.equals("null")){
			image.setImageBitmap(bitmap);
			image.setVisibility(View.VISIBLE);
		}
		
		int in = 0;
		for (int i = 0; i < options.size(); i++) {
			String[] data = new String[2];
			data = options.get(i);
			Button txt1 = new Button(getActivity());
		    txt1 = (Button) getLayoutInflater(getArguments()).inflate(R.layout.btnxml, null);			
			txt1.setText(data[1]);
			txt1.setLayoutParams(params);
			txt1.setId(i);
			// count++;
			final String pid = data[0];
			txt1.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// put code on click operation
					uploadSelection(pid);
				}
			});
			linearLayout.addView(txt1, in++);

		}
		psDialog.dismiss();
	}

	public void uploadSelection(String id) {
		psDialog = ProgressDialog.show(getActivity(), "", "Loading...");
		upload_poll_connection pollcon2 = new upload_poll_connection();
		pollcon2.execute(id);
	}

	public void showResult() {

		linearLayout.removeAllViews();
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		int in =0;
		for (int i = 0; i < options.size(); i++) {
			String[] data = new String[2];
			data = options.get(i);
			String c="0";
			for(int j=0;j<pollcount.size();j++){
				String[] data2 = pollcount.get(j);
				if(data[0].equals(data2[0])){
					c=data2[1];
				}
			}
			TextView txt1 = new TextView(getActivity());
			txt1.setText(data[1]+": "+c);
			txt1.setLayoutParams(params);
			linearLayout.addView(txt1, in++);

		}
		psDialog.dismiss();
	}

	class poll_connection extends AsyncTask<String, Integer, Integer> {

		@Override
		protected Integer doInBackground(String... params) {
			try {
				String link;
				if(params[0].equals(""))
					 link = "http://myfyp.no-ip.org/cs4295/getPoll.php";
				else
					 link = "http://myfyp.no-ip.org/cs4295/getPoll.php?pollid="+params[0];
				// execute http request
				HttpClient client = new DefaultHttpClient();
				HttpGet request = new HttpGet(link);
				HttpResponse response = client.execute(request);

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(response.getEntity().getContent()));
				// retrieve http response and save it as a string
				String reply = "";
				String t;
				reply = reader.readLine();
				while ((t = reader.readLine()) != null)
					reply += t;
				reader.close();
				if (!reply.equals("")) {
					// parse json
					JSONObject json = new JSONObject(reply);
					JSONArray listArray = json.getJSONArray("list");
					title = listArray.getJSONObject(0).getString("title");
					pollid = listArray.getJSONObject(0).getString("id");
					imageUrl = listArray.getJSONObject(0).getString("img");
					if(!imageUrl.equals("null")){
						String url = "http://myfyp.no-ip.org/cs4295/image/"+imageUrl;
						URL newurl = new URL(url); 
						bitmap = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
					}
					cmtcount = json.getJSONArray("list3").getJSONObject(0)
							.getString("count");
					JSONArray listArray2 = json.getJSONArray("list2");
					for (int i = 0; i < listArray2.length(); i++) {
						String[] cl = new String[2];
						JSONObject obj = listArray2.getJSONObject(i);
						cl[0] = obj.getString("optionid");
						cl[1] = obj.getString("option");
						options.add(cl);
					}
				}
			} catch (Exception e) {
				// Toast.makeText(this, "error " + reply,
				// Toast.LENGTH_LONG).show();
				// showToast(e.getMessage());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			showPoll();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

	}

	class upload_poll_connection extends AsyncTask<String, Integer, Integer> {

		@Override
		protected Integer doInBackground(String... params) {
			try {
				HttpPost httpRequest = new HttpPost(
						"http://myfyp.no-ip.org/cs4295/insertPollRecord.php");
				List<NameValuePair> list1 = new ArrayList<NameValuePair>();
				list1.add(new BasicNameValuePair("userid", "1"));
				list1.add(new BasicNameValuePair("pollid", pollid));
				list1.add(new BasicNameValuePair("optionid", params[0]));

				httpRequest.setEntity(new UrlEncodedFormEntity(list1,
						HTTP.UTF_8));
				HttpResponse response = new DefaultHttpClient()
						.execute(httpRequest);

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(response.getEntity().getContent()));
				// retrieve http response and save it as a string
				String reply="";
				String t;
				while (( t = reader.readLine()) != null)
					reply += t;
				reader.close();
				if (!reply.equals("")) {
					// parse json
					JSONObject json = new JSONObject(reply);
					JSONArray listArray = json.getJSONArray("list");
					for (int i = 0; i < listArray.length(); i++) {
						String[] cl = new String[2];
						JSONObject obj = listArray.getJSONObject(i);
						cl[0] = obj.getString("optionid");
						cl[1] = obj.getString("count");
						pollcount.add(cl);
					}
				}
			} catch (Exception e) {
				// Toast.makeText(this, "error " + reply,
				// Toast.LENGTH_LONG).show();
				// showToast(e.getMessage());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			showResult();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

	}

}
